var __MODULE__username = "";
var __MODULE__URL = "http://ws.audioscrobbler.com/1.0/user/%u/recenttracks.rss";
var __MODULE__noOfTracks = 5;

/*
 * Fetches the list
 */
function makeRequest(){
    var params = {};
    // params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
    var url = __MODULE__URL.replace("%u", __MODULE__username);

    _IG_FetchXmlContent(url, function(xml) {
        if(!xml) { _gel('recent-tracks').innerHTML = "Error retrieving data" ; return ; }

        var tracks = xml.getElementsByTagName('item');

        if(!tracks) { _gel('recent-tracks').innerHTML = "Error retrieving data" ; return ; }

        var html = "<a href=\"http://last.fm/user/" + 
                    __MODULE__username + "\">" + __MODULE__username +
                    "</a> recently heard <ul>";

        var len = Math.min(__MODULE__noOfTracks, tracks.length);
        for(i = 0 ; i < len ; i++) {
        var name = tracks[i].getElementsByTagName('title')[0];
        var link = tracks[i].getElementsByTagName('link')[0];
        html += '<li><a href="' + link.firstChild.nodeValue + '">'+name.firstChild.nodeValue+'</a></li>';
        }
        html+="</ul>";
        _gel('recent-tracks').innerHTML = html;
    });
}

function fetchUsernameAndList() {

    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
    req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.PersonId.OWNER, "lastfm-username"), 'data');

    req.send( function ( data ) {
        if(! data.hadError()) {
            var viewer = data.get('viewer').getData();
            var viewerData = data.get('data').getData()[viewer.getId()];
            if(viewerData) {
                __MODULE__username = viewerData['lastfm-username'];
            }
            else {
                _gel('recent-tracks').innerHTML = "<strong>User hasn't filled in his Last.fm username yet</strong>";
            }
            makeRequest( );
        }
        else {
            _gel('recent-tracks').innerHTML = "<strong>There was an error retreiving the username</strong>" ;
            console.log(data);
        }
    });
}


function checkOwnership() {
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
    req.send( function ( data ) {
        var viewer = data.get('viewer').getData();
        if( viewer.isOwner() ) {
            allowEditingUsername();
        }
    } );
}

function allowEditingUsername() {
    document.getElementById('username-div').style.display = "";
    document.getElementById('lastfm-username').value = __MODULE__username;
}

function saveUsername() {

    document.getElementById('lastfm-notification').innerHTML = "";
    document.getElementById('save-username').disabled = true ;

    var req = opensocial.newDataRequest();
    req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, "lastfm-username", document.getElementById('lastfm-username').value));
    req.send( function ( data ) {
        var status = "";
        if(! data.hadError() ) {
            status = "Username was Saved";
            fetchUsernameAndList();
        }
        else {
            status = "Error! Username could not be saved. Try again later";
        }
        document.getElementById('lastfm-notification').innerHTML = status;
        document.getElementById('save-username').disabled = false ;
    });
}

